<?php
/**
 * Created by PhpStorm.
 * User: nmw
 * Date: 17-9-1
 * Time: 上午11:19
 */

namespace SDK\Ali;

require_once(THINK_PATH . "/Library/Vendor/OpenSearch/Autoloader/Autoloader.php");

use OpenSearch\Client\OpenSearchClient;
use OpenSearch\Client\SearchClient;
use OpenSearch\Util\SearchParamsBuilder;

class AliyunSearch
{
    /**
     * @var string
     */
    protected $accessKeyId = "LTAIubsbHSREtSht";

    /**
     * @var string
     */
    protected $secret = "JH3TTP26iz68Bi8n6bkiSaskxktQNJ";

    /**
     * @var string
     */
    protected $endPoint = "http://opensearch-cn-hangzhou.aliyuncs.com";

    /**
     * @var array
     */
    protected $options = ['debug' => TRUE];

    /**
     * @var
     */
    protected $client;

    /**
     * AliyunSearch constructor.
     */
    public function __construct()
    {
        $this->client = new OpenSearchClient(
            $this->accessKeyId, $this->secret, $this->endPoint, $this->options
        );
    }

    /**
     * 开放搜索-搜索全部
     *
     * @param $appName
     * @param $keyWord
     * @param $operate
     * @param $start
     * @param $limit
     * @param array $fields
     * @param string $filter
     * @param array $sort
     * @return array
     */
    public function searchAll($appName, $keyWord, $operate, $start, $limit, $fields = [], $filter = '', $sort = [])
    {
        $result = [];

        if (empty($appName))
        {
            return $result;
        }

        $searchClient = new SearchClient($this->client);
        //创建参数对象，并指定对应参数
        $params = new SearchParamsBuilder();
        $params->setStart($start);
        $params->setHits($limit);
        //设置应用名称
        $params->setAppName($appName);
        //设置查询query
        $query = '';

        foreach ($keyWord as $kwKey => $kwItem)
        {
            if (0 != $kwKey)
            {
                $query .= " {$operate} ";
            }

            $query .= "{$kwItem['key']}:'{$kwItem['search']}'";
        }

        $params->setQuery($query);

        //设置返回格式
        $params->setFormat("fulljson");
        //添加排序
        if (!empty($sort))
        {
            foreach ($sort as $sItem)
            {
                $params->addSort($sItem[0], $sItem[1]);
            }
        }

        //设置文档过滤条件
        $params->setFilter($filter);

        //设置需返回哪些字段
        if (!empty($fields))
        {
            $params->setFetchFields($fields);
        }

        //执行查询并返回信息
        $ret = $searchClient->execute($params->build());
        $rs = json_decode($ret->result, TRUE);

        if ('OK' == $rs['status'])
        {
            $result = array_column($rs['result']['items'], 'fields');
        }

        return $result;
    }
}